// Main JavaScript for Green Ammonia Energy Storage Website

// Smooth scrolling function
function scrollToSection(sectionId) {
    const element = document.getElementById(sectionId);
    if (element) {
        element.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
}

// Initialize animations and interactions
document.addEventListener('DOMContentLoaded', function() {
    // Initialize scroll animations
    initScrollAnimations();
    
    // Initialize navigation highlighting
    initNavigationHighlight();
    
    // Initialize molecule animation
    initMoleculeAnimation();
    
    // Initialize counter animations
    initCounterAnimations();
    
    // Initialize chart animations
    initChartAnimations();
});

// Scroll animations using Intersection Observer
function initScrollAnimations() {
    const observerOptions = {
        threshold: 0.1,
        rootMargin: '0px 0px -50px 0px'
    };

    const observer = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                // Add animation class
                entry.target.classList.add('animate-in');
                
                // Specific animations for different elements
                if (entry.target.classList.contains('tech-card')) {
                    anime({
                        targets: entry.target,
                        translateY: [30, 0],
                        opacity: [0, 1],
                        duration: 600,
                        easing: 'easeOutQuad',
                        delay: Math.random() * 200
                    });
                }
                
                if (entry.target.classList.contains('financial-metric')) {
                    anime({
                        targets: entry.target,
                        scale: [0.9, 1],
                        opacity: [0, 1],
                        duration: 500,
                        easing: 'easeOutBack',
                        delay: Math.random() * 300
                    });
                }
            }
        });
    }, observerOptions);

    // Observe elements for animation
    document.querySelectorAll('.tech-card, .financial-metric, .ammonia-molecule').forEach(el => {
        observer.observe(el);
    });
}

// Navigation highlighting based on scroll position
function initNavigationHighlight() {
    const sections = document.querySelectorAll('section[id]');
    const navLinks = document.querySelectorAll('nav a[href^="#"]');

    window.addEventListener('scroll', () => {
        let current = '';
        sections.forEach(section => {
            const sectionTop = section.offsetTop;
            const sectionHeight = section.clientHeight;
            if (scrollY >= sectionTop - 200) {
                current = section.getAttribute('id');
            }
        });

        navLinks.forEach(link => {
            link.classList.remove('text-teal-400', 'font-semibold');
            link.classList.add('text-slate-300');
            if (link.getAttribute('href') === `#${current}`) {
                link.classList.remove('text-slate-300');
                link.classList.add('text-teal-400', 'font-semibold');
            }
        });
    });
}

// Animate ammonia molecule
function initMoleculeAnimation() {
    const molecules = document.querySelectorAll('.ammonia-molecule');
    
    molecules.forEach(molecule => {
        const atoms = molecule.querySelectorAll('.molecule-atom');
        
        // Rotate atoms around center
        anime({
            targets: atoms,
            rotate: '360deg',
            duration: 4000,
            loop: true,
            easing: 'linear',
            delay: function(el, i) {
                return i * 500;
            }
        });
    });
}

// Animate numbers counting up
function initCounterAnimations() {
    const counters = document.querySelectorAll('[data-count]');
    
    const counterObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const target = entry.target;
                const finalValue = parseFloat(target.getAttribute('data-count'));
                const duration = 2000;
                
                anime({
                    targets: { value: 0 },
                    value: finalValue,
                    duration: duration,
                    easing: 'easeOutQuad',
                    update: function(anim) {
                        const currentValue = anim.animatables[0].target.value;
                        if (target.getAttribute('data-count').includes('.')) {
                            target.textContent = currentValue.toFixed(1) + target.getAttribute('data-suffix');
                        } else {
                            target.textContent = Math.round(currentValue) + target.getAttribute('data-suffix');
                        }
                    }
                });
                
                counterObserver.unobserve(target);
            }
        });
    });
    
    counters.forEach(counter => {
        counterObserver.observe(counter);
    });
}

// Enhanced chart animations
function initChartAnimations() {
    // Add loading animations to charts
    const chartContainers = document.querySelectorAll('[id$="Chart"]');
    
    chartContainers.forEach(container => {
        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    // Add loading animation
                    container.style.opacity = '0';
                    anime({
                        targets: container,
                        opacity: [0, 1],
                        duration: 800,
                        easing: 'easeOutQuad'
                    });
                    
                    observer.unobserve(container);
                }
            });
        });
        
        observer.observe(container);
    });
}

// Add hover effects to interactive elements
function addHoverEffects() {
    // Tech cards hover effect
    document.querySelectorAll('.tech-card').forEach(card => {
        card.addEventListener('mouseenter', function() {
            anime({
                targets: this,
                scale: 1.02,
                duration: 300,
                easing: 'easeOutQuad'
            });
        });
        
        card.addEventListener('mouseleave', function() {
            anime({
                targets: this,
                scale: 1,
                duration: 300,
                easing: 'easeOutQuad'
            });
        });
    });
    
    // Button hover effects
    document.querySelectorAll('button').forEach(button => {
        button.addEventListener('mouseenter', function() {
            anime({
                targets: this,
                scale: 1.05,
                duration: 200,
                easing: 'easeOutQuad'
            });
        });
        
        button.addEventListener('mouseleave', function() {
            anime({
                targets: this,
                scale: 1,
                duration: 200,
                easing: 'easeOutQuad'
            });
        });
    });
}

// Initialize hover effects after DOM load
document.addEventListener('DOMContentLoaded', addHoverEffects);

// Utility function for debouncing
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// Smooth scroll for navigation links
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();
        const targetId = this.getAttribute('href').substring(1);
        scrollToSection(targetId);
    });
});

// Add loading animation for images
document.querySelectorAll('img').forEach(img => {
    img.addEventListener('load', function() {
        anime({
            targets: this,
            opacity: [0, 1],
            duration: 500,
            easing: 'easeOutQuad'
        });
    });
});

// Performance optimization: Lazy load charts
const lazyLoadCharts = debounce(() => {
    const charts = document.querySelectorAll('[id$="Chart"]');
    charts.forEach(chart => {
        const rect = chart.getBoundingClientRect();
        if (rect.top < window.innerHeight && rect.bottom > 0) {
            // Chart is in viewport, initialize if not already done
            if (!chart.classList.contains('initialized')) {
                chart.classList.add('initialized');
                // Trigger chart initialization
                if (typeof echarts !== 'undefined') {
                    const chartInstance = echarts.getInstanceByDom(chart);
                    if (chartInstance) {
                        chartInstance.resize();
                    }
                }
            }
        }
    });
}, 100);

window.addEventListener('scroll', lazyLoadCharts);
window.addEventListener('resize', lazyLoadCharts);